package org.mbcorp.sar.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.mbcorp.sar.dao.AreaDAO;
import org.mbcorp.sar.model.Area;
import org.mbcorp.sar.service.AreaService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("areaService")
public class AreaServiceImpl implements AreaService {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(AreaServiceImpl.class);

	@Resource
	private AreaDAO areaDAO;

	@Transactional
	@Override
	public Area grabar(Area created) {
		LOGGER.debug("Creando nueva area con informacion: " + created);

		return areaDAO.save(created);
	}

	@Override
	public Area eliminar(Integer areaId)
			throws RuntimeException {
		LOGGER.debug("Eliminando area con id: " +  areaId);

		Area eliminado =  areaDAO.findOne(areaId);

		if (eliminado == null) {
			LOGGER.debug("No se encontro area con id: " + areaId);
			throw new RuntimeException();
		}

		areaDAO.delete(eliminado);
		return eliminado;
	}

	@Transactional(readOnly = true)
	@Override
	public List<Area> buscarTodos() {
		LOGGER.debug("Buscando todas las areas");
		return areaDAO.findAll();
	}

	@Transactional(readOnly = true)
	@Override
	public Area buscarPorId(Integer id) {
		LOGGER.debug("Buscando area con id: " + id);
		return areaDAO.findOne(id);
	}

	@Transactional
	@Override
	public Area actualizar(Area actualizado)
			throws RuntimeException {
		LOGGER.debug("Actualizando area con informacion: " + actualizado);

		Area area = areaDAO.findOne(actualizado.getId());

		if (area == null) {
			LOGGER.debug("No se encontro area con id: "
					+ actualizado.getId());
			throw new RuntimeException();
		}

		return area;
	}

}
